package dk.rhok.findstufffast;



import android.graphics.*;
import android.graphics.drawable.*;
import android.location.*;
import com.google.android.maps.*;



public class MapManager extends ViewManager
{
    private MapActivity mapActivity;
    private GeoPoint phone;
    private GeoPoint target;

    private Drawable targetMarker;
    private Drawable phoneMarker;

    private TargetOverlay targetOverlay;


    



    public MapManager(MapActivity mapActivity)
    {
        //super(R.layout.map, 4f, 8f);
        super(R.layout.map, Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY);



        this.mapActivity = mapActivity;
    }



    public void update(Location phoneLocation, 
                       Location targetLocation)
    {
        MapView mapView = (MapView) mapActivity.findViewById(R.id.map2);
        MapController controller = mapView.getController();

        int pLa = (int)(1e6 * phoneLocation.getLatitude());
        int pLo = (int)(1e6 * phoneLocation.getLongitude());
        int tLa = (int)(1e6 * targetLocation.getLatitude());
        int tLo = (int)(1e6 * targetLocation.getLongitude());
        
        phone = new GeoPoint(pLa, pLo);
        target = new GeoPoint(tLa, tLo);
        GeoPoint centerPoint = new GeoPoint((pLa + tLa)/2, (pLo + tLo)/2);

        controller.zoomToSpan(Math.abs(pLa - tLa), Math.abs(pLo - tLo));
        controller.setCenter(centerPoint);

        if(targetOverlay == null)
        {
            targetMarker = mapActivity.getResources().getDrawable(R.drawable.fsfmarker);
            phoneMarker = mapActivity.getResources().getDrawable(R.drawable.androidmarker);
            targetOverlay = new TargetOverlay();
            mapView.getOverlays().add(targetOverlay);
        }
        targetOverlay.onChange();
    }



    private class TargetOverlay extends ItemizedOverlay
    {
        public TargetOverlay()
        {
            super(targetMarker);
        }

        @Override
        protected OverlayItem createItem(int index)
        {
            if(index == 0)
                return new OverlayItem(target, "Heart Starter", "Heart Starter");
            else
            {
                OverlayItem phoneItem = new OverlayItem(phone, "You", "You");
                phoneItem.setMarker(phoneMarker);
                return phoneItem;
            }
        }

        @Override
        public int size()
        {
            return 2;
        }

        public void onChange()
        {
            populate();
        }

        public void draw(Canvas canvas, MapView mapView, boolean shadow)
        {
            super.draw(canvas, mapView, shadow);
            boundCenterBottom(targetMarker);
            boundCenterBottom(phoneMarker);
        }
    }
}